package cn.wildfire.chat.kit.search;

import android.content.Context;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.appcompat.widget.SearchView;

import com.sourcemuch.im.caiba.R;import com.sourcemuch.im.caiba.R2;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import cn.wildfire.chat.app.extendsion.classes.FriendRequestFromSource;
import cn.wildfire.chat.kit.WfcBaseActivity;
import cn.wildfirechat.model.Conversation;

/**
 * 如果启动{@link android.content.Intent}里面包含keyword，直接开始搜索
 */
public abstract class SearchActivity extends WfcBaseActivity {

    /**
     * 仅搜索用户
     */
    public static final int TYPE_USER_SEARCH = 0;
    /**
     * 本地数据搜索及线上用户搜索
     */
    public static final int TYPE_MORE_SEARCH = 1;

    /**
     * 仅搜索联系人
     */
    public static final int TYPE_CONTACT_SEARCH = 2;

    /**
     * 其他类型搜索
     */
    public static final int TYPE_ONLY_SEARCH = -1;

    private SearchFragment searchFragment;
    private List<SearchableModule> modules = new ArrayList<>();
    protected SearchView searchView;

    /**
     * 自定义主题栏
     */
    protected LinearLayout searchLayout;
    protected TextView cancleTxt;
    protected EditText searchEdittext;

    /**
     * modify by HEKE , 2019/8/26 18:28
     * TODO 搜索类型
     */
    protected int searchType = TYPE_USER_SEARCH;
    public Conversation mConversation;

    /**
     * 不同搜索界面标签区分
     */
    private String styleTag;

    @Override
    protected int contentLayout() {
        return R.layout.search_portal_activity;
    }

    public int getSearchType() {
        return searchType;
    }

    public void setSearchType(int searchType) {
        this.searchType = searchType;
    }

    public void setStyleTag(String styleTag) {
        this.styleTag = styleTag;
    }

    @Override
    protected void afterViews() {
        initView();
        FriendRequestFromSource.fromsource = FriendRequestFromSource.ADD_FROM_SEARCH_TEXT;
    }

    /**
     * 设置进入提示语
     *
     * @param hintText
     */
    public void setEditHintText(String hintText) {
        if (searchEdittext == null) {
            return;
        }
        searchEdittext.setHint(hintText);
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            try {
                searchEdittext.setFocusable(true);
                searchEdittext.setFocusableInTouchMode(true);
                searchEdittext.setCursorVisible(true);
                searchEdittext.requestFocus();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected int menu() {
        return R.menu.search_portal;
    }

    @Override
    protected void afterMenus(Menu menu) {
        MenuItem searchItem = menu.findItem(R.id.menu_search);
        //通过MenuItem得到SearchView
        searchView = (SearchView) searchItem.getActionView();
        //initSearchView();
        String initialKeyword = getIntent().getStringExtra("keyword");
        if (!TextUtils.isEmpty(initialKeyword)) {
            searchView.setQuery(initialKeyword, true);
        }
    }

    @Override
    protected void setTitleCenterThenSetSearchView() {
        super.setTitleCenterThenSetSearchView();
        cheatViews();
    }

    /**
     * 使用控件替代
     */
    private void cheatViews() {
        try {
            /**
             * modify by HEKE , 2019/8/28 18:35 TODO 动态修改Toolbar内容
             */
            setToolbarOrReplaceType(true, 3);
            if (this instanceof SearchMessageActivity) {
                boolean isGroupInfo = (mConversation.type == Conversation.ConversationType.Group);
                setReplaceTitle(null, isGroupInfo ? R.string.found_talk_records_content : R.string.found_talk_records);
            } else {
                setReplaceTitle(null, R.string.search);
            }
            setSearchLayoutVisibility(false);
            searchEdittext = findViewById(R.id.searchEditText);
            String queryHint = getResources().getString(R.string.search);
            if (!cn.wildfire.chat.app.extendsion.utils.TextUtils.isTextEmpty(styleTag)) {
                if (styleTag.equals("add_friend")) {
                    setReplaceTitle(null, R.string.add__friend);
                    queryHint = getResources().getString(R.string.xintui_or_mobile);
                }
            }
            searchEdittext.setHint(queryHint);
            searchEdittext.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                }

                @Override
                public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                }

                @Override
                public void afterTextChanged(Editable editable) {
                    try {
                        /**
                         * modify by HEKE , 2019/8/23 15:29
                         * TODO 搜索功能限制及修改
                         */
                        String s = editable.toString();
                        if (searchType == TYPE_USER_SEARCH) {
                            if (!cn.wildfire.chat.app.extendsion.utils.TextUtils.isTextEmpty(s)) {
                                boolean number = isInteger(s);
                                if (number) {
                                    if (s.length() >= 6) {
                                        search(s);
                                    }
                                } else {
                                    search(s);
                                }
                            }
                        } else {
                            search(s);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
            searchEdittext.setOnKeyListener(new View.OnKeyListener() {
                @Override
                public boolean onKey(View view, int i, KeyEvent keyEvent) {
                    if (keyEvent.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
                        search(searchEdittext.getText().toString());
                    }
                    return false;
                }
            });
            searchEdittext.setFocusable(true);
            searchEdittext.requestLayout();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initView() {
        searchFragment = new SearchFragment();
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.containerFrameLayout, searchFragment)
                .commit();
        initSearchModule(modules);
    }

    private boolean isInteger(String str) {
        Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
        return pattern.matcher(str).matches();
    }

    public void search(String keyword) {
        if (!TextUtils.isEmpty(keyword)) {
            searchFragment.search(keyword, modules);
        } else {
            searchFragment.reset();
        }
    }

    /**
     * @param modules 是一个输出参数，用来添加希望搜索的{@link SearchableModule}
     */
    protected abstract void initSearchModule(List<SearchableModule> modules);

    /**
     * 输入法弹出与隐藏
     */
    private void showInputMethod() {
        InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    }

}
